<template>
  <div>
    <!-- 玩法说明 -->
    <Guide :isShow="state.guideVisible" @handleClose="state.guideVisible = false" />

    <div class="game-top">
      <div class="go_home" @click="goHome">返<br />回<br/>首<br/>页</div>
      <!-- <div class="u_num">
        <img :src="assetsImageUrl + 'images/u_num.png'" alt="" />
        {{state.u_num}}U星能
      </div> -->
     
    </div>
    <div class="rule-prize">
      <!-- <img src="/images/home/rule-icon.png" alt="" @click="()=>  state.rulePage = true"> -->
      <div class="toolbar-btn" @click="handleShare">
        <div class="text-vertical">
          <span>分</span>
          <span>享</span>
        </div>
      </div>
      </div>
    <div>
      <!-- 进度条 -->
      <div class="jumping_load" id="J_loadLayer" v-if="state.showLoad">
        <div class="center">
          <div class="robot"></div>
          <div class="process">
            <div class="curr_process"></div>
          </div>
        </div>
      </div>

      <!-- S 主舞台 -->
      <div class="jumping_game" id="phaser" ref="phaser">
        <div class="bg_box">
        </div>
      </div>
    </div>

    <div class="footer">
      <!-- <div class="ranking" @click="goRanking"><img :src="assetsImageUrl + 'images/ranking.png'" alt="" /></div> -->
      <div class="dice"></div>
      <!-- <div class="prizebox">
        <img v-show="state.endData.category === 1" :src="assetsImageUrl + 'images/reward_icon1.png'" alt="" />
        <img v-show="state.endData.category === 2" :src="assetsImageUrl + 'images/reward_icon2.png'" alt="" />
        <img v-show="state.endData.category === 3" :src="assetsImageUrl + 'images/reward_icon3.png'" alt="" />
        <img v-show="state.endData.category === 4" :src="assetsImageUrl + 'images/reward_icon4.png'" alt="" />
      </div> -->
      <div class="roll_dice" @click="handleRollDice">
        <img :src="assetsImageUrl + '/images/roll_dice.png'" alt="">
        <!-- <p class="remain-times">今日剩余{{ state.numTimes }}次机会</p> -->
      </div>
      <!-- <div class="box_shadow"><div class="tr_t">开启挑战</div></div> -->
    </div>
<!-- 分享示范 -->
<Share v-if="state.show_share_indication" @handleClose="state.show_share_indication = false"></Share>
    <!-- 奖励弹窗 -->
    <MyPopover
      :title="state.popoverTitle"
      :isShow="state.myPopoverPage"
      :tips="state.popoverTips"
      :icon="state.popoverIcon"
      :category="state.category"
      @handleClose="handleClose">
      <template v-if="state.popoverTips">获得<br /></template>
      <div class="popover-msg" v-html="state.popoverMsg "></div>
    </MyPopover>
    <SharePopover 
      :is-show="state.showShare"
      @handleClose="onGetNum"
    />
    <NeedShare 
    :is-show="state.showNeedShare"
    @handleClose="handleShare"
    :title="state.popoverMsg"
    />
    <GameOver 
      :is-show="state.showGameOver"
      :title="state.popoverMsg"
      close
      @handle-close="Object.assign(state,{showGameOver:false,loading:false})"
    />
  </div>
</template>

<script setup>
import { showToast, showLoadingToast, closeToast } from 'vant';
import 'vant/es/toast/style';
import { reactive, ref, onMounted, nextTick, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import MyPopover from "../components/MyPopover.vue";
import Guide from '../components/guide.vue';
import "../assets/css/game/index.css";
import gameAll from "../assets/js/game/main.js";
import utils from "../utils";
import { gameTimes, gameStart, gameEnd, getScore,shareRecord } from "../api/index"
import Share from '../components/ShareIndication.vue'
import SharePopover from '../components/SharePopover.vue'
import NeedShare from '../components/NeedShare.vue'
import GameOver from '../components/GameOver.vue';
import canvasConfetti from 'canvas-confetti'
const route = useRouter();
const assetsImageUrl = ref(import.meta.env.VITE_ASSETS_IMAGE_URL)
function celebrate() {
  const box = document.getElementById(`box`);

  let count = 200;
  let defaults = {
    zIndex: 9999,
    origin: {
      x: 0.5,
      // since they fall down, start a bit higher than random
      y: .5 || 0
    }
  };

  function fire(particleRatio, opts) {
    canvasConfetti(
      Object.assign({}, defaults, opts, {
        particleCount: Math.floor(count * particleRatio)
      })
    );
  }

  fire(0.25, {
    spread: 26,
    startVelocity: 55
  });
  fire(0.2, {
    spread: 60
  });
  fire(0.35, {
    spread: 100,
    decay: 0.91,
    scalar: 0.8
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 25,
    decay: 0.92,
    scalar: 1.2
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 45
  });
}
const state = reactive({
  loading: false,
  numTimes: 0,
  // successPage: false,
  myPopoverPage: false,
  guideVisible: false,
  showLoad: true,
  isShow: false,
  game: {},
  popoverTitle: '',
  popoverIcon: null,
  popoverMsg: '',
  popoverTips: false,
  endData: {},
  u_num: 0,
  show_share_indication: false,
  category: null,
  showShare: false,
  showNeedShare: false,
  showGameOver: false,
  draw_share: false

});

function goHome() {
  route.push('/');
}

function goRanking() {
  route.push("/ranking");
}

const progressCallback = (data) => {
  state.showLoad = false;
  state.guideVisible = true;
}
function handleShare() {
  state.showNeedShare = false
  state.loading = false
  if (utils.getOperationEnvironment() == "uni_mini") {
    console.log("uni_mini")
    state.show_share_indication = true;
  } else {
    console.log("app")
    utils.callAppShare()
  }

  // 记录分享
  shareRecord().then((resp) => {

    setTimeout(() => {
      // console.log('fenxiangchenggong')
      console.log(resp,'resp')
      state.show_share_indication = false
      if (resp.data) {
        state.showShare = true
      }
      
      
    }, 3000);
  })
}
// 点击投掷按钮
async function handleRollDice() {
  if (state.loading) return;

  state.loading = true;
  // if (state.numTimes < 1) {
  //   state.myPopoverPage = true;
  //   state.popoverTitle = '很遗憾'
  //   state.popoverMsg = '今日次数已用完<br>请明日再来'
  //   state.popoverIcon = '/images/has-no-icon.png'
  //   state.popoverTips = false
  //   return;
  // }

  // 开始游戏
  await setGameStart();

  // 设置骰子动画
  const dice = document.querySelector('.dice');
  dice.style.backgroundImage = `url(${import.meta.env.VITE_ASSETS_IMAGE_URL}/images/dice-s-2.gif)`;

  // 随机点数
  const count = Math.ceil(Math.random() * 6)||3;

  // 设置骰子点数
  setTimeout(() => {
    dice.style.backgroundImage = `url(${import.meta.env.VITE_ASSETS_IMAGE_URL}/images/dice${count}.png)`;
  }, 1800)

  // 调用结束接口
  const endData = await setGameEnd(count);
  state.popoverIcon = '';
  // state.popoverIcon = endData.icon;

  // 移动步数
  setTimeout(() => {
    
    state.game.spriteMove(count, endData.category, async function() {
      console.log('end')
      state.myPopoverPage = true;
      state.popoverTitle = '恭喜您'
      state.popoverMsg = endData.category === 1 ? `${endData.name}` : `获得${endData.name}`
      state.popoverIcon = endData.icon
      state.category = endData.category
      state.popoverTips = false
      if (endData.category === 1) {
        
        state.popoverTips = true
      } else if (endData.category === 5) {
        state.popoverTitle = '谢谢参与！'
        state.popoverMsg = '您的福气在后头～'
        // state.popoverIcon = ''
      }
      console.log(endData.category)
      if([0,3,4].includes(endData.category)) {
        celebrate()
        console.log('xxxxxxxxxxxxxxxxxx')
        setTimeout(() => {
          console.log('yyyyyyyyyyy')
          state.endData = {...endData}
        }, 1600);
      } else {
        state.endData = { ...endData }
      }
      
      
      // await nextTick();
      // // 获取最新u星能
      // fetchScore();
    });
    getGameTimes();
  }, 3000)
}

// 监听页面加载完成
window.addEventListener("progress", progressCallback);

function handleClose() {
  
  state.myPopoverPage = false;
  
  nextTick(() => {
    state.loading = false
    if (state.draw_share) {
      state.showNeedShare = true
      state.popoverMsg = '很遗憾<br />您的投掷机会已用完<br/>分享可增加1次投掷机会'
    }
  })
}

// 游戏开始
function setGameStart() {
  
  return new Promise(resolve => {
    gameStart().then(res => {
      if(res.error_code === 1003) {
        state.popoverMsg = res.msg
        state.showNeedShare = true
        // state.loading = false
        return
      }
      // resolve()
      if (res.error_code === 999) {
        state.showGameOver = true
        state.popoverMsg = res.msg
        // state.loading = false
        return
      }
      resolve()
    }).catch((res) => {
      // state.loading = false
    //     state.myPopoverPage = true;
    // // state.popoverTitle = '很遗憾'
    // state.popoverMsg = res.msg || '开始游戏失败'
    // state.popoverIcon = '/images/has-no-icon.png'
    // state.popoverTips = false
    //   console.log(res,'xxxxxx')
    })
  })
}

// 游戏结束
function setGameEnd(dice_num) {
  return new Promise(resolve => {
    gameEnd({ dice_num }).then(res => {
      
      const { error_code,msg } = res || {};
      // let newCategory = 1;
      // if (category === 0) {
      //   newCategory = 1;
      // } else if (category === 3 || category === 4) {
      //   newCategory = 4;
      // } else if (category === 6) {
      //   newCategory = 2;
      // } else if (category === 7) {
      //   newCategory = 3;
      //   // setTimeout(() => {
      //   //   // 获取最新u星能
      //   //   fetchScore();
      //   // }, 1000)
      // } else if (category === 5) {
      //   newCategory = 5;
      // }
      
      if (error_code === 999) {
      state.myPopoverPage = true;
      state.popoverTitle = ''
      state.popoverMsg = msg
      state.popoverIcon = ''
      state.popoverTips = false
      return
      }
      const { data: { category, icon, name,draw_share } } = res || {}
      state.draw_share = draw_share
      const endData = { category, icon, name,draw_share }

      resolve(endData);
    }).catch(e => {
      console.log(e,'eeeee')
      state.myPopoverPage = true;
      state.popoverTitle = '很遗憾'
      state.popoverMsg = e.msg
      state.popoverIcon = ''
      state.popoverTips = false
    })
  })
}
// 点击去投掷
const onGetNum = () => {
  state.showShare = false
  // state.loading = false
  // getGameTimes()
  // setGameStart()
}
// 获取游戏剩余次数
function getGameTimes() {
  gameTimes().then(res => {
    const { data = {} } = res
    state.numTimes = data.remain_game_num || 0;
    // state.loading = false;
  })
}

// 获取U星能
function fetchScore() {
  getScore().then(res => {
    state.u_num = res.data;
  })
}

onMounted(() => {
  getGameTimes();
  // fetchScore();

  setTimeout(() => {
    state.game = new gameAll();
    state.game.init()
  }, 10);
});

onBeforeUnmount(() => {
  try {
    window.removeEventListener("progress", progressCallback)
  } catch (error) {

  }

});
</script>

<style  scoped>
div {
  font-family: "ChangAnunitype-Regular";
    font-size: 4vw;
}
.go_home,
.u_num {
  position: fixed;
  z-index: 99;
  top: 80px;
  /* height: 50px; */
  /* display: flex;
  flex-direction: column; */
  /* text-orientation: mixed; */
  background: linear-gradient(180deg, rgb(142,186,252) 0%, rgba(199,221,254,0.65) 93%, rgba(255,255,255,0.61961) 100%);
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
  line-height: 1;
  padding: 10px 8px;
  color: #fff;
}
.rule-prize {
  position: absolute;
  right: 0;
  top: 100px;
  /* width: 120px; */
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  z-index: 9;
}
.toolbar-btn {
  margin-bottom: 10px;
  padding: 0.5px 0 0.5px 0.5px;
}

.rule-prize .text-vertical {
  /* writing-mode: vertical-rl; */
  display: flex;
  flex-direction: column;
  /* text-orientation: mixed; */
  background: linear-gradient(180deg, rgb(142,186,252) 0%, rgba(199,221,254,0.65) 93%, rgba(255,255,255,0.61961) 100%);
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  line-height: 1;
  padding: 10px 8px;
  color: #fff;
}
.go_home {
  left: 0;
  /* width: 150px; */
}

.u_num {
  right: 20px;
  min-width: 200px;
  border-radius: 64px;
  padding-left: 25px;
}
.u_num > img {
  width: auto;
  height: 80px;
  position: absolute;
  left: -35px;
  margin-top: -5px;
}

.game-top {
  width: 100%;
  display: flex;
  height: 122px;
  justify-content: space-around;
  align-items: center;
  position: fixed;
  z-index: 9999;
}

.jumping_game {
  position: relative;
}

.bg_box {
  position: absolute;
  width: 100%;
  height: 100vh;
  z-index: -1;
  /* background: linear-gradient(183deg, #4c7de7 0, #1798da 20%); */
  background: linear-gradient(183deg, #73b2e7 0, #fdf0ed 70%);
  /* background: url('/images/game-base.png'); */
  /* background-size: 100% 100%; */
  
}

.bg_box>img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.footer {
  position: absolute;
  bottom: -30px;
  width: 100%;
  height: 370px;
  background: url("https://yinli-qixi-run.varwey.com/2023_ca/chess1025/images/game_footer.png") no-repeat;
  background-size: cover;
}

.footer .ranking {
  position: absolute;
  left: 15%;
  margin-left: -52px;
  margin-top: 40px;
}

.footer .ranking>img {
  width: 104px;
}

.footer .prizebox {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 164px;
  height: 164px;
  position: absolute;
  right: 14%;
  margin-right: -82px;
  margin-top: 10px;
  background: url('https://yinli-qixi-run.varwey.com/2023_ca/u_chess/images/prize_bg.png');
  background-size: cover;
}

.footer .prizebox img {
  width: 78px;
}

.footer .dice {
  position: absolute;
  left: 50%;
  top: 4%;
  width: 166px;
  height: 166px;
  background: url('https://yinli-qixi-run.varwey.com/2023_ca/u_chess/images/dice6.png');
  /* background-position: -770px 166px; */
  background-size: cover;
  margin-left: -83px;
  margin-top: -40px;
}

.footer .roll_dice {
  width: 279px;
  position: absolute;
  left: 50%;
  top: 38%;
  margin-left: -140px;
  text-align: center;
}

.footer .roll_dice>img {
  width: 100%;
}

.footer .roll_dice .remain-times {
  font-size: 18px;
  margin-top: 5px;
}

.text_active {
  color: #0160a5;
}

.score-num {
  flex: 1;
  justify-content: center;
  align-items: center;
  display: flex;
}
.popover-msg {
  
}
</style>